package com.jdkj.tools.controller;

import com.jdkj.tools.util.AjaxResult;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

import static com.jdkj.tools.util.ParseExelUtil.readTestCases;

@RestController
@RequestMapping("/testcase")
public class TestCaseController {

    /**
     * 上传测试数据（Excel 文件）
     * @param projectKey 前端 FormData 里的 projectKey
     * @param projectId 前端 FormData 里的 projectId
     * @param file       前端 FormData 里的 file
     */
    @PostMapping(
            value = "/uploadTestData",
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE  //类型是表单FormData数据
    )
    public AjaxResult uploadTestData(
            @RequestParam("projectKey") String projectKey,@RequestParam("projectId")String projectId,
            @RequestPart("file") MultipartFile file  //File类
    ) {
        if (file.isEmpty()) {
            return AjaxResult.error(400, "文件不能为空");
        }
        try {
            //先解析excel文件
            String tempDir = System.getProperty("java.io.tmpdir"); // 系统临时目录
            String fileName = UUID.randomUUID().toString() + ".xls";
            File tempFile = new File(tempDir, fileName);
            file.transferTo(tempFile);
            readTestCases(tempFile.getAbsolutePath(),projectKey,projectId);
            System.out.println("处理成功");
            return AjaxResult.success("上传并处理成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(500, "处理失败：" + e.getMessage());
        }
    }
}
